package com.pangolin.pangolinim.ui.fragment;

import android.content.Intent;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.lqr.recyclerview.LQRRecyclerView;
import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.R;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.sqlite.DBContact;
import com.pangolin.pangolinim.sqlite.DBSession;
import com.pangolin.pangolinim.ui.activity.MainActivity;
import com.pangolin.pangolinim.ui.adapter.RecentMessageAdapter;
import com.pangolin.pangolinim.ui.adapter.UIContact;
import com.pangolin.pangolinim.ui.adapter.UISession;
import com.pangolin.pangolinim.ui.base.BaseFragment;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.ImageUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class RecentMessageFragment extends BaseFragment {
    public LQRRecyclerView mRvRecentMessage;
    private RecentMessageAdapter mAdapter;
    public static List<UISession> mSessions = new ArrayList<UISession>();;

    @Override
    public void init() {
    }

    @Override
    public void initView(View rootView) {
        mRvRecentMessage = rootView.findViewById(R.id.rvRecentMessage);

        setAdapter();
    }

    @Override
    public void onResume() {
        super.onResume();
        //Logger.d("RecentMessageFragment onResume");
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_SESSIONS);
        BundleUtil bundleUtil  = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        ((MainActivity)getActivity()).BroadcastSender(bundleUtil.getBundle());
    }

    @Override
    public void onPause() {
        super.onPause();
        //Logger.d("RecentMessageFragment onPause");
    }

    @Override
    public void initData() {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_recent_message;
    }

    private void setAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRvRecentMessage.setLayoutManager(layoutManager);
        mAdapter = new RecentMessageAdapter(this , mSessions , ((MainActivity)getActivity()).me);
        mRvRecentMessage.setAdapter(mAdapter);
    }

    /**
     * TODO:修改单项会话信息
     * @param session 要修改的会话信息
     */
    public void setSession(UISession session){
        for (int i = 0 ; i < mSessions.size() ; i ++){
            if(mSessions.get(i).getUid() == session.getUid()){
                mSessions.get(i).setLastmsg(session.getLastmsg());
                mSessions.get(i).setMsgtype(session.getMsgtype());
                mSessions.get(i).setLasttime(session.getLasttime());
                mSessions.get(i).setUnread(mSessions.get(i).getUnread() + 1);
                break;
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * TODO:更新最近会话列表。为提高效率，如果最近会话列表不为空，则会判断新旧列表是否一致，只更新不一致的部分
     * @param sessions 要更新的最近会话列表
     */
    public void setSessions(List<DBSession> sessions){
        MainActivity activity = (MainActivity) getActivity();
        for (DBSession dbSession : sessions){
            //查找现有列表中是否有这个会话
            int i = findSessionById(dbSession.getUid());
            if(i >= 0){
                //判断现有列表中会话信息和dbSession是否一致，不一致则更新信息
                if(!dbSession.getName().equals(mSessions.get(i).getName())){
                    mSessions.get(i).setName(dbSession.getName());
                }
                if(!dbSession.getHeadimg().equals(mSessions.get(i).getHeader())){
                    mSessions.get(i).setHeader(dbSession.getHeadimg());
                    File file = new File(activity.getExternalFilesDir(String.valueOf(activity.me.getUid())) , dbSession.getHeadimg());
                    if(file.exists() && file.isFile()){
                        mSessions.get(i).setHeadimg(ImageUtil.getBitmapFromFile(activity , file , 120 , 120));
                    }
                }else{
                    //判断头像bitmap是否为空，如果为空则重新尝试读取头像
                    if(mSessions.get(i).getHeadimg() == null){
                        File file = new File(activity.getExternalFilesDir(String.valueOf(activity.me.getUid())) , dbSession.getHeadimg());
                        if(file.exists() && file.isFile()){
                            mSessions.get(i).setHeadimg(ImageUtil.getBitmapFromFile(activity , file , 120 , 120));
                        }
                    }
                }
                if(dbSession.getMsgtype() != mSessions.get(i).getMsgtype()){
                    mSessions.get(i).setMsgtype(dbSession.getMsgtype());
                }
                if(!dbSession.getLastmsg().equals(mSessions.get(i).getLastmsg())){
                    mSessions.get(i).setLastmsg(dbSession.getLastmsg());
                }
                if(!dbSession.getLasttime().equals(mSessions.get(i).getLasttime())){
                    mSessions.get(i).setLasttime(dbSession.getLasttime());
                }
                if(dbSession.getUnread() != mSessions.get(i).getUnread()){
                    mSessions.get(i).setUnread(dbSession.getUnread());
                }
            }else{
                //如果没有，直接创建这个会话信息
                UISession uiSession = new UISession();
                uiSession.setUid(dbSession.getUid());
                uiSession.setName(dbSession.getName());
                uiSession.setHeader(dbSession.getHeadimg());
                File file = new File(activity.getExternalFilesDir(String.valueOf(activity.me.getUid())) , uiSession.getHeader());
                if(file.exists() && file.isFile()){
                    uiSession.setHeadimg(ImageUtil.getBitmapFromFile(activity , file , 120 , 120));
                }
                uiSession.setMsgtype(dbSession.getMsgtype());
                uiSession.setLastmsg(dbSession.getLastmsg());
                uiSession.setLasttime(dbSession.getLasttime());
                uiSession.setUnread(dbSession.getUnread());
                mSessions.add(uiSession);
            }
        }
        //反向查找已经删除的条目
        Iterator item = mSessions.iterator();
        while (item.hasNext()) {
            UISession session = (UISession) item.next();
            int flag = -1;
            for (int j = 0 ; j < sessions.size() ; j ++){
                if (sessions.get(j).getUid() == session.getUid()){
                    flag = j;
                    break;
                }
            }
            if(flag < 0){
                item.remove();
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    public void removeUnread(int uid){
        MainActivity activity = ((MainActivity) getActivity());
        if(activity != null){
            //隐藏主界面未读消息标签
            activity.mTvMessageRedDot.setVisibility(View.GONE);
            //发送消息给服务，操作数据库移除未读消息
            Map<String, Object> brocastMap = new HashMap<String, Object>();
            brocastMap.put("type" , BroadcastMsg.DATA_UI_SETSESSION);
            brocastMap.put("uid" , uid);
            brocastMap.put("unread" , 0);
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
            activity.BroadcastSender(bundleUtil.getBundle());
        }
        for (int i = 0 ; i < mSessions.size() ; i ++){
            if(mSessions.get(i).getUid() == uid){
                mSessions.get(i).setUnread(0);
                break;
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    private int findSessionById(int uid){
        for (int i = 0 ; i < mSessions.size() ; i ++){
            if (mSessions.get(i).getUid() == uid){
                return i;
            }
        }
        return -1;
    }
}